import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "../../../components/ThePagination";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheQueryForm from '@/components/TheQueryForm';
import { getDateTime3 } from '@/utils/getDate'
import { apiDynamicCommentsPage, apiDynamicCommentsAudit } from '@/request/petCircleUtil/comments'
import store from "@/store/store"
import _ from 'lodash';
import { ExclamationCircleFilled } from "@ant-design/icons";
import GoBack from "@/components/TheGoBack";
import moment from 'moment';
import { Typography, Input } from 'antd';

const { TextArea } = Input;

// 评论列表
class Comments extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            textArea: "",
            storeId: "",
            sortOrder: {
                fields: '',
                order: ''
            },
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            total: 0,
            newColumns: [],
            form_show: true,
            source: false,
            searchOption: [
                {
                    field: 'commentsText',
                    label: '评论内容',
                    placeholder: '请输入',
                    required: false,
                    rules: [],
                    type: 'Input',
                    defaultValue: ''
                },
                {
                    field: 'nickName',
                    label: '用户昵称',
                    placeholder: '请输入',
                    required: false,
                    rules: [],
                    type: 'Input',
                    defaultValue: ''
                }, {
                    field: 'time',
                    label: '创建时间',
                    placeholder: '请选择',
                    required: false, rules: [],
                    type: 'RangePicker'
                },
                {
                    field: 'auditState',
                    label: '审核状态',
                    placeholder: '全部',
                    required: false,
                    rules: [],
                    type: 'Select',
                    options: [{ value: 1, label: '通过' }, { value: 0, label: '驳回' }],
                },
                // {
                //     field: 'configCarouselTitle',
                //     label: '敏感词',
                //     placeholder: '请输入',
                //     required: false,
                //     rules: [],
                //     type: 'Input',
                //     defaultValue: ''
                // },
                {
                    field: 'petCommentsId',
                    label: '编号',
                    placeholder: '请输入',
                    required: false,
                    stringMode: true,
                    type: 'InputNumber',
                },
                {
                    field: 'petDynamicId',
                    label: '动态编号',
                    placeholder: '请输入',
                    required: false,
                    stringMode: true,
                    type: 'InputNumber',
                },
                {
                    field: 'CommentsNum',
                    label: '评论数范围',
                    placeholder: '请输入',
                    required: false,
                    rules: [],
                    type: 'NumRange',
                    otherConfig: {
                        precision: 0,
                        max: Infinity,
                        min: 0
                    },
                    minKey: 'minCommentsNum',
                    maxKey: 'maxCommentsNum',
                },
                {
                    field: 'LikeNum',
                    label: '点赞数范围',
                    placeholder: '请输入',
                    required: false,
                    rules: [],
                    type: 'NumRange',
                    otherConfig: {
                        precision: 0,
                        max: Infinity,
                        min: 0
                    },
                    minKey: 'minLikeNum',
                    maxKey: 'maxLikeNum',
                },
                {
                    field: 'commentsUserType',
                    label: '评论主体',
                    placeholder: '请选择',
                    required: false,
                    rules: [],
                    type: 'Select',
                    options: [
                        { value: "SYSTEM", label: "运营" },
                        { value: "MEMBER", label: "用户" },
                    ],
                },
            ],
            queryForm: {},
        };
    }

    componentDidMount = async () => {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, pathName } = searchParams
        if (searchParams.source === "dynamic") {
            this.setState({
                source: true
            })
        }
        if (searchParams && pageNo && pathName == 'comments') {
            this.setState({
                queryForm,
                pageData: {
                    pageNo: pageNo,
                    pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData()
            })
        } else {
            await this.getData()
        }
        if (searchParams.source === "dynamic") {
            this.setState({
                source: true
            })
        }
    };

    audit(title, id) {
        this.setState({ modelTitle: title, visible: true, storeId: id })
    }

    handleCancel = () => {
        this.setState({ visible: false, storeId: '' });
    };
    //审核
    handleOk = async () => {
        const { textArea, modelTitle, storeId } = this.state
        if (!textArea) {
            return React.$message({
                type: 'error',
                content: `请输入${modelTitle}原因`
            })
        } else {
            const auditType = modelTitle === "驳回" ? '0' : '1'
            let res = await apiDynamicCommentsAudit({
                dataIdList: [storeId],
                auditReason: textArea,
                dataType: "2",
                auditType
            })
            if (res.code === 0) {
                this.setState({ visible: false }, () => {
                    this.getData()
                });
            }
        }
    };
    // 获取表格数据
    getData = async (values) => {
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.startTime = getDateTime3(values.time[0])
            values.endTime = getDateTime3(values.time[1])
            delete values.time
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            let { time, ...form } = { ...this.state.queryForm }
            const params = {
                pageNo,
                pageSize,
                queryForm: { ...form, time }
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'comments',
                    ...params
                }
            })
            let res = await apiDynamicCommentsPage({
                pageNo,
                pageSize,
                ...this.state.queryForm,
            })
            if (res.code === 0 && res.data) {
                this.setState({
                    dataSource: res.data,
                    pageData: {
                        pageNo: res.pageNo,
                        pageSize: res.pageSize
                    },
                    total: res.totalCount,
                })
            }
            // else if (res.code !== 0) {
            //     message.error(res.codeMessage)
            // }
        })
    };

    //查看详情
    goDetail(id) {
        this.props.history.push('/petCircleUtil/comments/' + id)
    }

    //时间排序
    sortTime(time) {
        return moment(time).unix()
    }

    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            },
            // source: false
        }, () => {
            this.getData()
        })
    };

    sorterFun = (pagination, filters, sorter) => {
        console.log(sorter.order, 'aaaa');
        this.sortOrder = null
        console.log(this.state.columns, 'sssss');
        this.setState({
            sortOrder: {
                fields: sorter.field,
                order: sorter.order
            }
        })
        delete this.state.queryForm['orderByAsc']
        delete this.state.queryForm['orderByDesc']
        let sortType = sorter.order // 排序类型，正序/倒叙/不排序
        if (sortType) {
            this.state.queryForm[sortType === 'ascend' ? 'orderByAsc' : 'orderByDesc'] = sorter.field
            this.getData()
        } else {
            this.getData()
        }
    }

    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }

    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }

    onFormSearch(values) {
        // console.log(values)
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 },
            sortOrder: {
                fields: '', order: null
            },
            // source: false
        }, () => {
            this.getData(values)
        })
    }

    render() {
        const {
            dataSource,
            source,
            pageData: { pageNo, pageSize },
            total,
            searchOption,
            form_show,
            visible,
            modelTitle,
        } = this.state;
        const columns = [
            {
                title: "编号",
                dataIndex: "petCommentsId",
                key: "petCommentsId",
            },
            {
                title: "动态编号",
                dataIndex: "petDynamicId",
                key: "petDynamicId",
                render: (_, render) => {
                    return (
                        <Typography.Text copyable={{ text: render.petDynamicId }}>
                            <TheButton onClick={() => this.props.history.push('/petCircleUtil/dynamic/view/' + render.petDynamicId)}>{render.petDynamicId}</TheButton>
                        </Typography.Text>
                    )
                }
            },
            {
                title: "用户昵称",
                dataIndex: "nickName",
                key: "nickName",
            },
            {
                title: "评论内容",
                dataIndex: "commentsText",
                key: "commentsText",
            },
            {
                title: "评论数",
                key: "commentsNum",
                dataIndex: "commentsNum",
                sorter: true,
                sortOrder: this.state.sortOrder.fields === 'commentsNum' ? this.state.sortOrder.order : null

            },
            {
                title: "点赞数",
                dataIndex: "likeNum",
                key: "likeNum",
                sorter: true,
                sortOrder: this.state.sortOrder.fields === 'likeNum' ? this.state.sortOrder.order : null
            },
            {
                title: "省",
                dataIndex: "province",
                key: "province",
            },
            {
                title: "创建时间",
                dataIndex: "createTime",
                key: "createTime",
                sorter: true,
                sortOrder: this.state.sortOrder.fields === 'createTime' ? this.state.sortOrder.order : null

            },
            {
                title: "敏感词",
                dataIndex: "sensitiveWords",
                key: "sensitiveWords",
            },
            {
                title: "审核状态",
                dataIndex: "auditState",
                key: "auditState",
                render: (_, render) => {
                    return ["驳回", "通过", "待审核"][render.auditState]
                }
            },
            {
                title: "审核时间",
                dataIndex: "auditTime",
                key: "auditTime",
                render: (_, render) => {
                    return render.auditTime || ""
                }
            },
            {
                title: "审核理由",
                dataIndex: "auditReason",
                key: "auditReason",
            },
            {
                title: "操作",
                fixed: "right",
                width: 200,
                render: (_, render) => {
                    return (
                        <div>
                            <TheButton haspermi={["petCircleUtil:comments:detail"]} onClick={() => this.goDetail(render.petCommentsId)}>查看详情</TheButton>
                        </div>
                    );
                },
            },
            {
                title: "审核",
                fixed: "right",
                width: 200,
                render: (_, render) => {
                    return (
                        <div>
                            {/* render.auditState == 2  待审核状态两个按钮同时显示 */}
                            {
                                (render.auditState == 0 || render.auditState == 2) &&
                                <TheButton haspermi={["petCircleUtil:comments:auditStateTrue"]} onClick={() => this.audit("通过", render.petCommentsId)}>通过</TheButton>
                            }
                            {
                                (render.auditState == 1 || render.auditState == 2) &&
                                <TheButton haspermi={["petCircleUtil:comments:auditStateFalse"]} onClick={() => this.audit("驳回", render.petCommentsId)}>驳回</TheButton>
                            }

                        </div>
                    );
                },
            },
        ]
        return (
            <div className={"p-layout-box commodity-content"}>
                {
                    source &&
                    <div style={{ marginBottom: "1em" }}><GoBack history={this.props.history} title={"返回动态列表"} />
                    </div>
                }
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                </TheQueryForm>
                <TheTable
                    // scroll={{ x: "max-content", y: '63vh' }}
                    columns={columns}
                    dataSource={dataSource}
                    onChange={this.sorterFun}
                    rowKey={'configCarouselId'}
                />
                <ThePagination
                    pageNo={pageNo}
                    pageSize={pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
                <TheDialog
                    title={
                        <div>
                            <ExclamationCircleFilled
                                style={{ color: "#FAAD14", marginRight: 10 }}
                            />
                            {'输入' + modelTitle + '原因'}
                        </div>
                    }
                    width={400}
                    visible={visible}
                    handleCancel={this.handleCancel}
                    handleOk={this.handleOk}
                >
                    <TextArea
                        onChange={(e) => this.setState({
                            textArea: e.target.value
                        })}
                        allowClear
                        autoSize={{ minRows: 6, maxRows: 6 }}
                        maxLength={20}
                        showCount
                    />
                </TheDialog>
            </div>
        );
    }
}

export default Comments;
